package com.kly.user.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.fqgj.common.api.Response;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.exception.enums.BasicMsgCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;

@Activate(group = Constants.PROVIDER)
public class ExceptionFilter implements Filter {
    public static final Logger logger = LoggerFactory.getLogger(ExceptionFilter.class);


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result = null;
        try {
            result = invoker.invoke(invocation);
            Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            Class returnType = method.getReturnType();
            if (result.hasException()) {
                Throwable throwable = result.getException();

                if (returnType.getName().equals("com.fqgj.common.api.Response")) {
                    Response callResult;
                    if (throwable instanceof ApplicationException) {
                        callResult = Response.error(throwable.getMessage());
                    } else {
                        callResult = Response.error(BasicMsgCodeEnum.INTERNAL_SERVER_ERROR);
                    }
                    logger.error("服务异常 callResult={}", callResult, result.getException());
                    return new RpcResult(callResult);
                }
            }
            return result;

        } catch (Exception e) {
            logger.error("服务调用异常,调用方法及参数:{}:", new Object[]{invocation, e});
        }
        return result;
    }
}